﻿using System;
using System.Linq;

namespace Ones.Dal.Infrastructure
{
    public class AutoId
    {
        public String tryCreatePrefixId(string maxId, string prefixPart, int nDigits)
        {
            lock (this)
            {
                try
                {
                    string id = maxId;
                    string numPart = "";

                    if (String.IsNullOrEmpty(id))
                    {
                        for (int i = 0; i < nDigits - 1; i++)
                        {
                            numPart += "0";
                        }

                        id = prefixPart + numPart + "1";
                    }
                    else
                    {
                        int idNum = int.Parse(id.Substring(prefixPart.Length, nDigits));
                        idNum++;

                        for (int i = 0; i < nDigits; i++)
                        {
                            numPart += "0";
                        }

                        id = prefixPart + idNum.ToString(numPart);
                    }

                    return id;
                }
                catch (Exception)
                {
                    return null;
                }
            }
        }
    }
}